<?php

namespace app\index\service;

use app\admin\model\Userlist;
use app\common\model\Leader;
use app\common\model\Manager;
use app\common\model\Work;
use app\index\model\Propose;
use app\index\model\ProposeLog;
use think\Exception;

/**
 *User :门前一棵柿子树
 *Date:2024/4/14
 *Email:785313152@qq.com
 */
class ProposeService
{
    public $model;

    public function __construct()
    {

        $this->model = new Propose();
    }

    public function getAllList()
    {
        input('title') ? $where['title'] = ['like', '%' . input('title') . '%'] : '';
        $data = input();
        $data['question_type'] && $where['propsoe_type'] = ['=', $data['question_type']];
        $data['depart_id'] && $where['user_department'] = ['=', $data['depart_id']];

        input('page') ? $page = input('page') : 1;
        if (input('ismy')) {
            if (input('model') != 2) {
                $where['status'] = ['neq', ''];
                $where['create_user'] = session('user_info')['userid'];
            }
            if (input('model') == 2) {
                $where['status'] = ['neq', ''];
                $where['solution_user_id'] = session('user_info')['userid'];
            }
        } else {
            $data['status'] !== '' && $where['status'] = ['=', $data['status']];
        }
        return $this->model
            ->field('p.*,c.name as cate_name')
            ->alias('p')
            ->join('propose_classify c', 'p.propsoe_type = c.id')
            ->where($where)->order('add_time desc,status asc')->page($page, 5)->select();
    }

    public function approvalList()
    {
        $leader = new Leader();
        $manager = new Manager();
        $userid = session('user_info.userid');
        //部门领导
        $leader_department = $leader->where('JSON_CONTAINS(leader_user_list,\'"' . $userid . '"\')')->column('department_id');
        //分管领导
        $class_department = $leader->where('JSON_CONTAINS(class_user_list,\'"' . $userid . '"\')')->column('department_id');
        //hr
        $hr_user = json_decode($manager->where('id', '=', 4)->value('list'), true);

        if ($leader_department) {
            $where[] = "(status=1 AND user_department in (" . implode(',', $leader_department) . "))";
            $where[] = "(status=4 and solution_department in (" . implode(',', $leader_department) . "))";
        }
        if ($class_department) {
            $where[] = "(status=2 AND user_department in (" . implode(',', $leader_department) . "))";
        }
        if (in_array($userid, $hr_user)) {
            $where[] = "(status=3)";
        }
        $title = input('title');
        $list = $this->model;
        if ($title) {
            $list = $list->where('title', 'like', "%{$title}%");
        }
        $where[] = "(status=5 AND solution_user_id='{$userid}')";
        return $list->where(implode(' OR ', $where))->select();
    }


    public function getInfoStatus($id)
    {
        $info = $this->model->find($id)->toArray();
        $userid = session('user_info.userid');
        $is_auth = 0;
        //部门领导权限
        if ($info['status'] == 1) {
            $leader = Leader::where('department_id', '=', $info['user_department'])->value('leader_user_list');
            $leader = json_decode($leader, true);
            if (in_array($userid, $leader)) {
                $is_auth = 1;
            }
        }
        //分管领导权限
        if ($info['status'] == 2) {
            $leader = Leader::where('department_id', '=', $info['user_department'])->value('class_user_list');
            $leader = json_decode($leader, true);
            if (in_array($userid, $leader)) {
                $is_auth = 1;
            }
        }
//        人事部权限
        if ($info['status'] == 3) {
            $leader = Manager::where('id', '=', 4)->value('list');
            $leader = json_decode($leader, true);
            if (in_array($userid, $leader)) {
                $is_auth = 1;
            }
        }
//        解决部门领导权限
        if ($info['status'] == 4) {
            $leader = Leader::where('department_id', '=', $info['solution_department'])->value('leader_user_list');
            $leader = json_decode($leader, true);
            if (in_array($userid, $leader)) {
                $is_auth = 1;
            }
        }
//        解决人权限
        if ($info['status'] == 5) {
            $leader[] = $info['solution_user_id'];
            if ($userid == $info['solution_user_id']) {
                $is_auth = 1;
            }
        }
        $leaderInfo = Userlist::where('id', 'in', $leader)->column('name');
        return ['is_auth' => $is_auth, 'status' => $info['status'], 'leader' => implode(',', $leaderInfo)];
    }


    public function publish()
    {
        $data = input('post.');
        //判断提议人部门是否设置了领导及分管领导
        $leaderInfo = Leader::where('department_id', '=', $data['user_department'])->findOrFail()->toArray();
        $leader_user_list = json_decode($leaderInfo['leader_user_list']);
        $class_user_list = json_decode($leaderInfo['class_user_list']);
        if (!$leader_user_list) {
            return ajax_return(2, '请先联系管理员设置部门领导');
        }
        if (!$class_user_list) {
            return ajax_return(2, '请先联系管理员设置部门分管领导');
        }
        $data['create_user'] = session('user_info.userid');
        $data['create_user_info'] = [
            'name' => session('user_info.name'),
            'userid' => session('user_info.userid'),
            'avatar' => session('user_info.avatar')
        ];
        $allowField = [
            'title', 'create_user', 'create_user_info', 'user_department', 'add_time', 'propsoe_type', 'questiont', 'question_files', 'question_soluton', 'question_soluton_files', 'is_copyright', 'copyright_type'
        ];
        try {
            $data['add_time'] = date('Y-m-d H:i:s');
            $this->model->allowField($allowField)->save($data);
            $id = $this->model->id;
            //增加日志
            $log = new ProposeLog();
            $log->addLog($id, "提交了建议《{$data['title']}》");

        } catch (Exception $exception) {
            return ajax_return(3, '数据插入失败，' . $exception->getMessage());
        }
        //发送通知给部门领导
        $work = new Work();
        $work->send_templete_message($leader_user_list
            , '审核通知',
            '您部门成员发布了新的合理化建议需求，需要您进行审核，请前往处理。提议名称:' . $data['title'],
            site_url . '/index/propose/detail?id=' . $id);
        return ajax_return(1, '插入成功');

    }

    public function deny($id = 0)
    {
        $isAuth = $this->getInfoStatus($id);
        $info = $this->model->find($id)->toArray();
        $data = input('post.');
        if ($isAuth['is_auth'] == 1) {
            if ($info['status'] == 1) {
                $save['leader_content'] = $data['content'];
            }
            if ($info['status'] == 2) {
                $save['class_content'] = $data['content'];
            }
            if ($info['status'] == 3) {
                $save['hr_content'] = $data['content'];
            }
            $save['status'] = 0;
            $this->model->update($save, ['id' => $id]);
            //增加日志
            $log = new ProposeLog();
            $log->addLog($id, "驳回了该建议。" . $data['content']);
            $work = new Work();
            $work->send_templete_message([$info['create_user']]
                , '审核通知',
                "您发布的《{$info['title']}》审核没有通过，点击查看详情",
                site_url . '/index/propose/detail?id=' . $id);
            return ajax_return(1, '驳回成功');
        } else {
            return ajax_return(2, '权限验证失败');
        }
    }

    public function deal($id)
    {
        $info = $this->model->find($id)->toArray();
        $isAuth = $this->getInfoStatus($id);
        $data = input('post.');
        $leader = [];
        if ($isAuth['is_auth'] == 1) {
            $leaderInfo = [
                'userid' => session('user_info.userid'),
                'name' => session('user_info.name'),
                'avatar' => session('user_info.avatar'),

            ];
            if ($info['status'] == 1) {
                $save['leader_content'] = $data['content'];
                $save['status'] = 2;
                $save['leader_id'] = session('user_info.userid');
                $save['leader_user_info'] = $leaderInfo;
                $save['leader_apprval_time'] = date('Y-m-d H:i:s');
                $content = "通过了该建议。" . $data['content'];
                $leader = Leader::where('department_id', '=', $info['user_department'])->value('class_user_list');
                $leader = json_decode($leader, true);
            }
            if ($info['status'] == 2) {
                $save['class_content'] = $data['content'];
                $content = "通过了该建议。" . $data['content'];
                $save['status'] = 3;
                $save['class_leader_id'] = session('user_info.userid');
                $save['class_user_info'] = $leaderInfo;
                $save['class_approval_time'] = date('Y-m-d H:i:s');
                $leader = Manager::where('id', '=', 4)->value('list');
                $leader = json_decode($leader, true);
            }
            if ($info['status'] == 5) {
                $save['solution_content'] = $data['content'];
                $save['solution_user_info'] = $leaderInfo;
                $save['solution_time'] = date('Y-m-d H:i:s');
                $content = "完成了该建议。" . $data['content'];
                $save['status'] = 6;
            }
            $this->model->update($save, ['id' => $id]);
            //增加日志
            $log = new ProposeLog();
            $log->addLog($id, $content);
            $work = new Work();
            $work->send_templete_message([$info['create_user']]
                , '审核通知',
                "您发布的《{$info['title']}》审核已经通过/完成，点击查看详情",
                site_url . '/index/propose/detail?id=' . $id);
            if ($leader) {
                $work->send_templete_message($leader
                    , '审核通知',
                    "关于建议《{$info['title']}》需要您的审核，点击查看详情",
                    site_url . '/index/propose/detail?id=' . $id);
            }
            return ajax_return(1, '操作成功');
        } else {
            return ajax_return(2, '权限验证失败');
        }
    }


    public function choose($id)
    {
        $info = $this->model->find($id)->toArray();
        $isAuth = $this->getInfoStatus($id);
        if ($isAuth['is_auth'] != 1) {
            return ajax_return(2, '权限验证失败');
        }
        $data = input('post.');

        $leader = Leader::where('department_id', '=', $data['departid'])->value('leader_user_list');
        $leader = json_decode($leader);
        if (!$leader) {
            return ajax_return(2, '该部门未设置直属领导，请先设定直属领导');
        }
        if (!$data['departid']) {
            return ajax_return(2, '请选择执行部门');
        }
        $save = [
            'status' => 4,
            'hr_id' => session('user_info.userid'),
            'hr_user_info' => [
                'userid' => session('user_info.userid'),
                'name' => session('user_info.name'),
                'avatar' => session('user_info.avatar'),

            ],
            'hs_approval_time' => date('Y-m-d H:i:s'),
            'hr_content' => $data['content'],
            'solution_department' => $data['departid']
        ];
        $this->model->update($save, ['id' => $data['id']]);
        //增加日志
        $log = new ProposeLog();
        $log->addLog($id, "分配任务给{$data['department']}" . $data['content']);
        $work = new Work();
        $work->send_templete_message($leader
            , '合理化建议派发通知',
            "《{$info['title']}》审核已经通过，需要您设定执行成员，点击查看详情",
            site_url . '/index/propose/detail?id=' . $id);
        return ajax_return(1, '操作成功');
    }

    public function choose_user($id)
    {
        $info = $this->model->find($id)->toArray();
        $isAuth = $this->getInfoStatus($id);
        if ($isAuth['is_auth'] != 1) {
            return ajax_return(2, '权限验证失败');
        }
        $data = input('post.');
        if (!$data['complete_user_id']) {
            return ajax_return(2, '请选择执行人');
        }
        $save = [
            'status' => 5,
            'solution_leader_id' => session('user_info.userid'),
            'solution_leader_info' => [
                'userid' => session('user_info.userid'),
                'name' => session('user_info.name'),
                'avatar' => session('user_info.avatar'),

            ],
            'solution_sure_time' => date('Y-m-d H:i:s'),
            'solution_leader_content' => $data['content'],
            'solution_user_id' => $data['complete_user_id']
        ];
        $this->model->update($save, ['id' => $data['id']]);
        //增加日志
        $log = new ProposeLog();
        $log->addLog($id, "分配任务给{$data['complete_user_name']}" . $data['content']);
        $work = new Work();
        $work->send_templete_message([$data['complete_user_id']]
            , '合理化建议派发通知',
            "《{$info['title']}》审核已经通过，需要您执行并完成，点击查看详情",
            site_url . '/index/propose/detail?id=' . $id);
        return ajax_return(1, '操作成功');
    }

}